package com.wxy.filter;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequest.Builder;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.wxy.config.jwtConfig;
import reactor.core.publisher.Mono;

@Component
public class autoGlobalFilter implements GlobalFilter,Ordered{
	private static final String[] paths= {"/html/login.html","/index/login","/html/error.html"};
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// TODO 自动生成的方法存根
		//1.获取request
		ServerHttpRequest request=exchange.getRequest();
		ServerHttpResponse response=exchange.getResponse();
		String path=request.getPath().toString();
		System.out.println(path);
		//2.判断是否要做登录拦截
		if(isTruePath(path))
			return chain.filter(exchange);
		//3.获取token
		List<HttpCookie> cookies = request.getCookies().get("token");
        if (cookies == null || cookies.isEmpty()) {
            // 没有找到 loginCookie，拒绝访问
        	response.setStatusCode(HttpStatus.UNAUTHORIZED);
			return response.setComplete();
        }
        HttpCookie loginCookie = cookies.get(0);
        String tokenString = loginCookie.getValue();
		//4.校验并解析token
		Map<String,Object> map=null;
		try {
			map=jwtConfig.checkTolen(tokenString);
		} catch (Exception e) {
			// TODO: handle exception
			response.setStatusCode(HttpStatus.UNAUTHORIZED);
			return response.setComplete();
		}
		
		int id=(int) map.get("userId");
		//5.传递用户信息
		final String idString=Integer.toString(id);
 		ServerWebExchange newExchange=exchange.mutate()
				.request(new Consumer<Builder>() {
					@Override
					public void accept(Builder builder) {
						builder.header("userId",idString);
					}
				})
				.build();
		//6.放行
		return chain.filter(newExchange);
	}
	@Override
	public int getOrder() {
		// TODO 自动生成的方法存根
		return 0;
	}
	public static boolean isTruePath(String path) {
		for (String string : paths) {
			if(string.equals(path))
				return true;
		}
		if(path.contains("sc"))
			return true;
		return false;
	}
}
